<?php

declare(strict_types=1);

namespace App\Controller\Api;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\UserMiddleware;
use App\Model\User as ModelUser;
use App\Utils\JwtToken;
use App\Utils\StrUtils;
use EasyWeChat\Factory;
use Hyperf\Guzzle\CoroutineHandler;

/**
 * @AutoController(prefix="/api/user")
 */
class User extends AbstractController
{
    public function mplogin() {
        $this->validate([
            'code' => 'required',
            'encrypted_data' => 'required',
            'iv' => 'required'
        ]);

        $params = $this->request->all();

        $wxapp = Factory::miniProgram(config('wx.mp'));
        $wxapp['guzzle_handler'] = CoroutineHandler::class; // 协程
        $session = $wxapp->auth->session($params['code']);
        $openid = $session['openid'];

        $user = ModelUser::query()->where('openid', $openid)->first();
        if ($user == null) {
            $user = new ModelUser();
            $user->uuid = StrUtils::genUuid();
        }
        $user->openid = $openid;

        $decrypted = $wxapp->encryptor->decryptData($session['session_key'], $params['iv'], $params['encrypted_data']);

        $user->phone = $decrypted['phoneNumber'] ?? $user->phone;
        $user->save();

        $token = JwtToken::encode([
            // 'id' => $user->id,
            // 'openid' => $user->openid,
            'uuid' => $user->uuid,
        ]);
        $user->token = $token;
        
        return $this->success($user);
    }

    public function testLogin() {
        $token = JwtToken::encode([
            // 'id' => 1,
            'uuid' => '423302EE-6E93-7FA1-9A91-EF627BD9642F',
        ]);
        return $this->success($token);
    }

    /**
     * @Middlewares({
     *     @Middleware(UserMiddleware::class)
     * })
     */
    public function profile() {
        $user = ModelUser::query()->where('uuid', $this->request->getHeader('uuid')[0])->first();
        return $this->success($user);
    }

    /**
     * @Middlewares({
     *     @Middleware(UserMiddleware::class)
     * })
     */
    public function mpUserInfo() {
        $params = $this->request->all();
        // $user = ModelUser::find($this->request->getHeader('user_id')[0]);
        $user = ModelUser::query()->where('uuid', $this->request->getHeader('uuid')[0])->first();
        $user->nickname = $params['nickname'] ?? $user->nickname;
        $user->avatar = $params['avatar'] ?? $user->avatar;
        $user->save();
        return $this->success($user);
    }
}
